import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { getProjectInfoApi } from '@/common/apis/project/index.ts';
import { getProjectMemberDetail } from '@/common/apis/projectMember/index.ts';
import { useRoute } from 'vue-router';
import { useUserStore } from '@/store/modules/user.ts';

export const useProjectStore = defineStore('project', () => {
  const route = useRoute();
  const userStore = useUserStore();
  const userProjectInfo = ref({});
  const projectInfo = ref({
    id: 0,
    name: '',
    description: '',
    create_time: '',
    creator_name: '',
    creator_id: '',
  });
  const currentProjectPermissions = ref<string[]>([]);
  const isLoading = ref(false);
  const lastProjectId = ref<number | null>(null);
  // 获取用户在该项目下的信息
  const setUserProjectInfo = async (id: number, projectId: number) => {
    try {
      const { data } = await getProjectMemberDetail({ id, projectId });
      userProjectInfo.value = data;
    } catch (error) {}
  };

  const getUsefProjectInfo = () => {
    return userProjectInfo.value;
  };

  // 获取项目详情
  const setProjectInfo = async (projectId: number) => {
    try {
      const { data } = await getProjectInfoApi({ projectId });
      projectInfo.value = data;
    } catch {}
  };

  const getProjectInfo = () => {
    return projectInfo.value;
  };

  // 获取当前项目id
  const currentProjectId = computed(() => {
    return Number(route.params.id);
  });

  // 检查是否需要重新获取权限
  const shouldRefreshPermissions = computed(() => {
    return lastProjectId.value !== currentProjectId.value;
  });

  // // 获取项目权限
  // const getProjectPermissions = async (projectId?: number) => {
  //   const targetProjectId = projectId || currentProjectPermissions.value;
  //   if (!targetProjectId || !userStore.userInfo?.id) {
  //     console.warn('缺少项目Id或用户信息');
  //     return;
  //   }
  //   // 如果项目ID没有变化且已有权限信息，直接返回
  //   if (!shouldRefreshPermissions.value && currentProjectPermissions.value) {
  //     return currentProjectPermissions.value;
  //   }

  //   isLoading.value = true;
  //   try {
  //     const { data } = await getProjectPermissionsApi({
  //       id: userStore.userInfo?.id,
  //       projectId: targetProjectId,
  //     });
  //     currentProjectPermissions.value = data;
  //     lastProjectId.value = Number(targetProjectId);
  //     console.log('项目权限获取成功');
  //     return currentProjectPermissions.value;
  //   } catch (error) {
  //     console.error('获取项目权限失败:', error);
  //     currentProjectPermissions.value = [];
  //     return [];
  //   } finally {
  //     isLoading.value = false;
  //   }
  // };

  // 清除权限缓存
  const clearPermissions = () => {
    currentProjectPermissions.value = [];
    lastProjectId.value = null;
  };

  return {
    projectInfo,
    setProjectInfo,
    getProjectInfo,
    userProjectInfo,
    setUserProjectInfo,
    getUsefProjectInfo,
    // getProjectPermissions,
    clearPermissions,
    currentProjectPermissions,
  };
});
